package com.example.study_manger.control;

import com.example.study_manger.entity.Organization;
import com.example.study_manger.entity.Role;
import com.example.study_manger.entity.TrainingPlan;
import com.example.study_manger.entity.UserTb;
import com.example.study_manger.repository.OrganizationRe;
import com.example.study_manger.repository.TrainingPlanRe;
import com.example.study_manger.repository.UserTbRe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class TrainingPlanController {
    @Autowired
    private UserTbRe userTbRe;
    @Autowired
    private TrainingPlanRe trainingPlanRe;
    @Autowired
    OrganizationRe organizationRe;
    @PostMapping("/getPlanList")
    public List<TrainingPlan> getPlanList(@RequestBody String username){
        username=username.substring(0,username.length()-1);
        System.out.println(username);
        Role role = userTbRe.findByUsername(username).getRole();
        if (role.getRoleName().equals("superAdmin")){
            return trainingPlanRe.findAllByCreator(role);
        }
        return null;
    }
    @PostMapping("/addPlan/{username}")
    public List<TrainingPlan> addPlan(@PathVariable String username, @RequestBody TrainingPlan trainingPlan){
        Role role = userTbRe.findByUsername(username).getRole();
        if (role.getRoleName().equals("superAdmin")){
            trainingPlan.setCreator(role);
        }
        trainingPlanRe.save(trainingPlan);
        return null;
    }
    @PostMapping("/planDelete/{id}")
    public String PlanDelete(@PathVariable Long id){
        try {
            trainingPlanRe.deleteById(id);
            return "success";
        }catch (RuntimeException e){
            return "error";
        }
    }
    @PostMapping("/updatePlan")
    public String updatePlan(@RequestBody TrainingPlan trainingPlan){
        try {
            trainingPlanRe.save(trainingPlan);
            return "success";
        }catch (RuntimeException e){
            return "error";
        }
    }
}
